package com.atsmart.app.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.telephony.CellLocation;
import android.util.Log;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.activity.NavActivity;
import com.atsmart.app.model.NumberRequsetInfo;
import com.atsmart.app.model.NumberRequsetListInfo;
import com.atsmart.app.model.NumberResponseInfo;
import com.atsmart.app.model.NumberResponseListInfo;
import com.atsmart.app.model.PositionAttributeInfo;
import com.atsmart.app.receiver.HistoryReceiver;
import com.atsmart.app.receiver.SendReceiver;
import com.atsmart.app.sql.NumberSqlHelper;
import com.atsmart.app.sql.PositionSqlHelper;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
//import com.atsmart.log.UserLog;
import com.google.json.Gson;

public class infoService extends Service {

	private NumberSqlHelper nsql = null;
	private PowerManager.WakeLock wakeLock = null;
	private static long choosen = 0;
	private static int dur = 0;
	private PositionSqlHelper psql = null;
	public static infoService instance = null; 
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		instance = this;
		try {
			BizApp.getInstance().getmLocationClient().start();
		} catch (Exception e) {
			e.printStackTrace();
//			UserLog.getInstance().writeException(e);
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		try {
			Log.e("infoService", "infoService");
			wakeLock = acquireWakeLock();
			relesseWakeLock();
//			UserLog.getInstance().write("infoService , 当前时间" + StringUtil.getCurrentTime());
			BizApp.getInstance().setSendtime(System.currentTimeMillis());
			PositionAttributeInfo pinfo = null;
			boolean flag = checkSheetTime();
			psql = new PositionSqlHelper();
			psql.open(BizApp.getInstance().getSqlHelper());
			pinfo = psql.getAttribute();
			// nsql.deleteAttribute();
			if (dur != 0 && dur != pinfo.getDur()) {
				choosen = 0;
			}
			if(pinfo.getDur() != 0){
				if (choosen % (pinfo.getDur() / 60) == 0) {
					choosen = 0;
				}
			}
			dur = pinfo.getDur();

			nsql = new NumberSqlHelper();
			nsql.open(BizApp.getInstance().getSqlHelper());
			Calendar cal1 = Calendar.getInstance();
			if(pinfo.getDur() != 0){
			
			if (dur != 0 && flag && choosen % (pinfo.getDur() / 60) == 0) {
				choosen++;
//				UserLog.getInstance().write("infoService -> SendReceiver , 当前时间" + StringUtil.getCurrentTime() + ", choosen: = " + choosen);
				try {
					if (BizApp.getInstance().keeping) {
						BizApp.getInstance().getmLocationClient().stop();
					}
				} catch (Exception e) {
					e.printStackTrace();
//					UserLog.getInstance().writeException(e);
				}

//				wakeLock = acquireWakeLock();
				CellLocation.requestLocationUpdate();
//				relesseWakeLock();

				Intent intent1 = new Intent(getApplicationContext(),
						SendReceiver.class);
				
//				 Log.e("infosevice", "启动巡检Receiver");
				
				PendingIntent pi1 = PendingIntent.getBroadcast(
						getApplicationContext(), 1028, intent1, 0);
//				UserLog.getInstance().write("infoService -> SendReceiver , 当前时间" + StringUtil.getCurrentTime());
				AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
				am.set(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(), pi1);

//				
//				try {
//					if (BizApp.getInstance().keeping) {
////						getMes();
//					}
//				} catch (Exception e) {
//				}

			} else {
				choosen++;
			}
			}
			Intent intent2 = new Intent(getApplicationContext(),
					HistoryReceiver.class);
//			
			PendingIntent pi2 = PendingIntent.getBroadcast(
					getApplicationContext(), 1028 * 2, intent2, 0);
//
			AlarmManager amhis = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
			amhis.set(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(), pi2);
		} catch (Exception e) {
			e.printStackTrace();
//			UserLog.getInstance().writeException(e);
		}

//		return START_NOT_STICKY;
		return START_REDELIVER_INTENT;
	}

	private void relesseWakeLock() {
		if (wakeLock != null && wakeLock.isHeld()) {
			wakeLock.release();
			wakeLock = null;
		}
	}

	private PowerManager.WakeLock acquireWakeLock() {
		try {

			PowerManager localPowerManager = (PowerManager) getSystemService("power");
			if (localPowerManager != null) {
				String str1 = infoService.class.getName();
				PowerManager.WakeLock localWakeLock = null;
			 
				if (android.os.Build.MODEL.equals("HUAWEI Y 220T")
						|| android.os.Build.MODEL.equals("ZTE-U V880")
						|| android.os.Build.MODEL.equals("HUAWEI C8813Q")
						|| android.os.Build.MODEL.equals("ZTE V889D")) {
				 
					localWakeLock = localPowerManager.newWakeLock(
							PowerManager.SCREEN_DIM_WAKE_LOCK
									| PowerManager.ACQUIRE_CAUSES_WAKEUP, str1);
				} else {
					localWakeLock = localPowerManager.newWakeLock(
							PowerManager.PARTIAL_WAKE_LOCK, str1);

				}
				if (localWakeLock != null)
					localWakeLock.acquire();
				if (localWakeLock != null && localWakeLock.isHeld())
					localWakeLock.release();
				return localWakeLock;
			} else {
				return null;
			}

		} catch (Exception localException) {
			localException.printStackTrace();
//			UserLog.getInstance().writeException(localException);
			return null;
		}

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		if (BizApp.getInstance().getmLocationClient() != null) {
			try {
				BizApp.getInstance().getmLocationClient().stop();
			} catch (Exception e) {
//				UserLog.getInstance().writeException(e);
			}

		}
	}

	@Override
	public void onStart(Intent intent, int startid) {
		// TODO Auto-generated method stub
		// acquireWakeLock();

	}

	private boolean checkSheetTime() {
		try {
			BizApp.getInstance().start = false;
			BizApp.getInstance().end = false;
			PositionSqlHelper psql = new PositionSqlHelper();
			psql.open(BizApp.getInstance().getSqlHelper());
			PositionAttributeInfo inf = psql.getAttribute();

			int week = 0;
			int hour = 0;
			int min = 0;

			if (inf != null) {

				Calendar c = Calendar.getInstance();
				week = c.get(Calendar.DAY_OF_WEEK) - 1;

				hour = c.get(Calendar.HOUR_OF_DAY);
				min = c.get(Calendar.MINUTE);

				String sheet = inf.sheet;

				int dur = inf.getDur() * 1000;
				// Log.e("dur", dur+"");
				BizApp.getInstance().num = inf.getDur() / 60;

				String[] sheets = sheet.split(";");
				for (int i = 0; i < sheets.length; i++) {
					String weeks = sheets[i];
					String[] weekc = weeks.split(",");
					if (week == Integer.valueOf(weekc[0])) {
						if (Integer.valueOf(weekc[1]) == 1) {
							if (weekc.length == 2) {
								return true;
							}
							if (weekc.length == 6) {
								// return true;
								long ab = getMill(weekc[2], weekc[3])
										- StringUtil.FormDateToTime(StringUtil
												.getFullReportTime());
								// Log.e("ab", String.valueOf(Math.abs(ab) <
								// dur));
								// saveToSDCard("checkSheetTime.txt",
								// String.valueOf(ab) + "\r\n");
								if (Math.abs(ab) < dur) {
									BizApp.getInstance().start = true;
								}
								long ac = getMill(weekc[4], weekc[5])
										- StringUtil.FormDateToTime(StringUtil
												.getFullReportTime());
								if (Math.abs(ac) < dur) {
									BizApp.getInstance().end = true;
								}
								if (hour > Integer.valueOf(weekc[2])
										&& (hour < Integer.valueOf(weekc[4]) || hour == Integer
												.valueOf(weekc[4])
												&& min <= Integer
														.valueOf(weekc[5]))) {
									return true;
								}
								if (hour == Integer.valueOf(weekc[2])
										&& min >= Integer.valueOf(weekc[3])
										&& (hour < Integer.valueOf(weekc[4]) || hour == Integer
												.valueOf(weekc[4])
												&& min <= Integer
														.valueOf(weekc[5]))) {

									return true;
								}
							}
							if (weekc.length == 10) {
								// return true;
								long ab = getMill(weekc[2], weekc[3])
										- StringUtil.FormDateToTime(StringUtil
												.getFullReportTime());
								if (Math.abs(ab) < dur) {
									BizApp.getInstance().start = true;
								}
								long ac = getMill(weekc[4], weekc[5])
										- StringUtil.FormDateToTime(StringUtil
												.getFullReportTime());
								if (Math.abs(ac) < dur) {
									BizApp.getInstance().end = true;
								}
								long ad = getMill(weekc[6], weekc[7])
										- StringUtil.FormDateToTime(StringUtil
												.getFullReportTime());
								if (Math.abs(ad) < dur) {
									BizApp.getInstance().start = true;
								}
								long ae = getMill(weekc[8], weekc[9])
										- StringUtil.FormDateToTime(StringUtil
												.getFullReportTime());
								if (Math.abs(ae) < dur) {
									BizApp.getInstance().end = true;
								}
								if (hour > Integer.valueOf(weekc[2])
										&& (hour < Integer.valueOf(weekc[4]) || hour == Integer
												.valueOf(weekc[4])
												&& min <= Integer
														.valueOf(weekc[5]))) {
									return true;
								}
								if (hour == Integer.valueOf(weekc[2])
										&& min >= Integer.valueOf(weekc[3])
										&& (hour < Integer.valueOf(weekc[4]) || hour == Integer
												.valueOf(weekc[4])
												&& min <= Integer
														.valueOf(weekc[5]))) {
									return true;
								}
								if (hour > Integer.valueOf(weekc[6])
										&& (hour < Integer.valueOf(weekc[8]) || hour == Integer
												.valueOf(weekc[8])
												&& min <= Integer
														.valueOf(weekc[9]))) {
									return true;
								}
								if (hour == Integer.valueOf(weekc[6])
										&& min >= Integer.valueOf(weekc[7])
										&& (hour < Integer.valueOf(weekc[8]) || hour == Integer
												.valueOf(weekc[8])
												&& min <= Integer
														.valueOf(weekc[9]))) {
									return true;
								}
							}
						}
					}
				}
				return false;
			} else {
				return false;
			}

		} catch (Exception e) {
//			UserLog.getInstance().writeException(e);
		}
		return false;
	}

	private long getMill(String hour, String min) {
		try {
			String str = StringUtil.getFormTime();
			return StringUtil.FormDateTomill(str + " " + hour + ":" + min);
		} catch (Exception e) {
//			UserLog.getInstance().writeException(e);
		}
		return 0;
	}

	private NumberResponseListInfo getNum() {
		try {
			List<NumberResponseInfo> nums = nsql.getNumberInfo();
			// Log.e("num0", new Gson().toJson(nums));
			NumberRequsetListInfo linums = new NumberRequsetListInfo();
			List<NumberRequsetInfo> lis = new ArrayList<NumberRequsetInfo>();
			for (NumberResponseInfo num : nums) {
				NumberRequsetInfo rt = new NumberRequsetInfo();
				if (num.getLastTime() != 0) {
					rt.setType(num.getType());
					rt.setLastTime(num.getLastTime());
				}
				lis.add(rt);
			}
			linums.setVers(lis);

			// Log.e("nums", new Gson().toJson(linums));
			return ServiceHelper.getInstance().postData(
					ServiceHost.updateNumberURL(), new Gson().toJson(linums),
					NumberResponseListInfo.class);
		} catch (Exception e) {
//			UserLog.getInstance().writeException(e);
			return null;
		}
	}

//	private void getMes() {
//		try {
//			NumberResponseListInfo listinfo = getNum();
//			// Log.e("listinfo", new Gson().toJson(listinfo));
//			if (listinfo != null && listinfo.getVers() != null) {
//				StringBuffer sbf = new StringBuffer();
//				List<NumberResponseInfo> list = listinfo.getVers();
//				for (NumberResponseInfo info : list) {
//					if (info.getNumber() != 0) {
//						if (info.getType() == 1) {
//							sbf.append("任务数" + info.getNumber());
//						}
//						// if(info.getType()==2){
//						// sbf.append("瀹㈡埛锛�+info.getNumber());
//						// }
//						// if(info.getType()==3){
//						// sbf.append("妯℃澘锛�+info.getNumber());
//						// }
//						if (info.getType() == 4) {
//							sbf.append(" 消息数" + info.getNumber());
//						}
//						// if(info.getType()==6){
//						// sbf.append("浜у搧缁勶細"+info.getNumber());
//						// }
//						// if(info.getType()==7){
//						// sbf.append("浜у搧锛�+info.getNumber());
//						// }
//						NumberResponseInfo at = nsql.getNumberByType(info
//								.getType());
//						if (at == null) {
//							at = new NumberResponseInfo();
//							at.setLastTime(info.getLastTime());
//							at.setNumber(info.getNumber());
//							at.setType(info.getType());
//							nsql.addNumberInfo(at);
//						} else {
//							nsql.updateAttribute(info.getNumber(),
//									info.getType());
//						}
//
//					}
//				}
//				if (sbf.length() > 0) {
//					int icon = R.drawable.icon;
//					String tickerText = "更新提醒";
//					long when = (System.currentTimeMillis());
//					Notification nfc = new Notification(icon, tickerText, when);
//					nfc.defaults |= Notification.DEFAULT_SOUND;
//					nfc.defaults |= Notification.DEFAULT_VIBRATE;
//					nfc.defaults |= Notification.DEFAULT_LIGHTS;
//					// 璁╁０闊炽�鎸姩鏃犻檺寰幆锛岀洿鍒扮敤鎴峰搷搴�
//					// nfc.flags |= Notification.FLAG_INSISTENT;
//
//					// 閫氱煡琚偣鍑诲悗锛岃嚜鍔ㄦ秷澶�
//					nfc.flags |= Notification.FLAG_AUTO_CANCEL;
//
//					Context cxt = BizApp.getInstance().getApplicationContext();
//					String expandedTitle = "更新提醒";
//					String expandedText = sbf.toString();
//					// intent鏄潪甯搁噸瑕佺殑鍙傛暟,鐢ㄦ潵鍚姩浣犲疄闄呮兂鍋氱殑浜嬫儏,璁句负null鍚庣偣鍑荤姸鎬佹爮涓婄殑Notification灏辨病鏈変换浣曞弽搴斾簡.
//					Intent int1 = new Intent(BizApp.getInstance()
//							.getBaseContext(), NavActivity.class);
//					PendingIntent nfcIntent = PendingIntent.getActivity(cxt, 0,
//							int1, 0);
//					nfc.setLatestEventInfo(cxt, expandedTitle, expandedText,
//							nfcIntent);
//					// 鍙戦�Notification
//					NotificationManager nfcManager = (NotificationManager) BizApp
//							.getInstance().getSystemService(
//									Context.NOTIFICATION_SERVICE);
//					nfcManager.notify(1, nfc);
//				}
//			}
//		} catch (Exception e) {
//		}
//	}

}
